<template>
  <div>
    <el-button type="primary" plain icon="plus" @click="showDialog">
      新增
    </el-button>
    <el-dialog
      title="新增员工"
      v-model="dialogVisible"
      width="50%"
      style="border-radius: 10px; padding: 5px 10px"
      @closed="resetForm"
      @close-auto-focus="resetForm"
      destroy-on-close
    >
      <el-form
        label-position="right"
        label-width="87px"
        :model="commitForm"
        :rules="rules"
        ref="ruleFormRef"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="工号" prop="num">
              <el-input
                v-model.number="commitForm.num"
                placeholder="工号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="commitForm.name"
                placeholder="姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="tip">
              <svg-icon icon="tip" />
              <el-text size="small">
                该部门选项只是用来查询岗位，不作为新增内容
              </el-text>
            </div>
            <el-form-item label="部门">
              <el-tree-select
                v-model="deptId"
                style="width: 100%"
                :data="deptData"
                node-key="id"
                check-strictly
                :props="defaultProps"
              >
                <template #default="{ data }">
                  <span class="menu">
                    <span style="margin-right: 10px">{{ data.deptName }}</span>
                    <el-tag :type="levelType(data.level)" size="small">
                      {{ levelTest(data.level) }}
                    </el-tag>
                  </span>
                </template>
              </el-tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="regionId">
              <el-select
                v-model="commitForm.regionId"
                placeholder="地区"
                style="width: 100%"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.id"
                  :label="item.region"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select
                v-model="postIds"
                placeholder="岗位"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="item in postList"
                  :key="item.id"
                  :label="item.position"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="比例">
              <el-input
                v-model="commitForm.percents"
                placeholder="请按顺序输入，并以逗号间隔"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="级别" prop="grade">
              <el-input-number
                v-model="commitForm.grade"
                :precision="2"
                :step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="roleId">
              <el-select
                v-model="commitForm.roleId"
                placeholder="职务"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNum">
              <el-input
                v-model="commitForm.idNum"
                placeholder="身份证号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="commitForm.birthday"
                type="date"
                placeholder="出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input
                v-model="commitForm.email"
                placeholder="邮箱地址"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话1" prop="phoneNum1">
              <el-input
                v-model="commitForm.phoneNum1"
                placeholder="联系电话1"
                maxlength="11"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话2" prop="phoneNum2">
              <el-input
                v-model="commitForm.phoneNum2"
                placeholder="联系电话2"
                maxlength="11"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通信地址" prop="address">
              <el-input
                v-model="commitForm.address"
                placeholder="通信地址"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="commitForm.state">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="commitForm.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import dayjs from "dayjs";
import { addUser, getRegion, getPost } from "@/service/api/user";
import { getDeptTree } from "@/service/api/dept";
import { getAllRole } from "@/service/api/role";
import eventBus from "@/utils/event-bus";
import rules from "@/utils/rules";
import { toArray } from "@/utils/transform";

const ruleFormRef = ref();
const dialogVisible = ref(false);
const deptData = ref([]);
const regionList = ref([]);
const postList = ref([]);
const postIds = ref([]);
const deptId = ref("1");
const roleList = ref([]);

const defaultProps = {
  label: "deptName",
};
const commitForm = ref({
  id: null,
  num: null,
  name: null,
  postIdPercent: [],
  regionId: null,
  grade: 1.0,
  idNum: null,
  birthday: null,
  email: null,
  phoneNum1: null,
  phoneNum2: null,
  address: null,
  state: 1,
  remark: null,
  percents: "",
  postId: null,
  roleId: null,
});

const emit = defineEmits(["getUserList"]);

const showDialog = async () => {
  dialogVisible.value = true;
  regionList.value = await getRegion();
  postList.value = await getPost(deptId.value);
  deptData.value = await getDeptTree();
  roleList.value = await getAllRole();
  eventBus.emit("updateEmpId", null);
};

//提交表单
const submitForm = (formEl) => {
  formEl.validate(async (valid) => {
    if (valid) {
      let percentsArray = toArray(commitForm.value.percents);

      for (let i = 0; i < postIds.value.length; i++) {
        commitForm.value.postIdPercent.push({
          postId: postIds.value[i],
          percent: percentsArray[i],
        });
      }

      commitForm.value.birthday = dayjs(commitForm.value.birthday).format(
        "YYYY-MM-DD"
      );

      delete commitForm.value.postId;
      delete commitForm.value.percents;

      await addUser(commitForm.value);
      postIds.value = [];
      resetForm();
      emit("getUserList");
    } else {
      return false;
    }
  });
};

//重置表单内容
const resetForm = () => {
  ruleFormRef.value.resetFields();
  resetData();
  dialogVisible.value = false;
};

const levelType = (level) => {
  if (level === 1) return "";
  else if (level === 2) return "success";
  else if (level === 3) return "warning";
  else return "danger";
};

const levelTest = (level) => {
  if (level === 1) return "一级";
  else if (level === 2) return "二级";
  else if (level === 3) return "三级";
  else return "四级";
};
//重置数据
const resetData = () => {
  deptData.value = [];
  regionList.value = [];
  postList.value = [];
  postIds.value = [];
};

watch(
  () => deptId.value,
  async () => {
    postList.value = await getPost(deptId.value);
  }
);

watch(
  () => postIds.value,
  (newValue) => {
    if (newValue) commitForm.value.postId = newValue[0];
    else commitForm.value.postId = null;

    eventBus.emit("updatePostIds", newValue.length);
    ruleFormRef.value.validateField("percents");
  }
);
</script>
<style lang="scss">
.menu {
  display: inline-flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}
.tip {
  margin-left: 55px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  gap: 0.3125rem;
  .el-text {
    line-height: 12px;
  }
}
</style>
